//
//  MusicPlayer.m
//  LO_MUSIC
//
//  Created by 向祖华 on 16/2/26.
//  Copyright © 2016年 杨少锋. All rights reserved.
//

#import "MusicPlayer.h"
#import "AudioPlayer.h"
#import "LyricTool.h"
#import "MusicViewController.h"

static NSInteger numberOfIndexPath = 0;//记录当前播放歌曲的位置值
static CGFloat timeOfSongPlaying = 0;//记录歌播放的进度

@interface MusicPlayer ()<AudioPlayerDelegate,UITableViewDataSource,UITableViewDelegate>
//计时器
@property(nonatomic,strong)NSTimer*timer;//用于图片旋转
@property(nonatomic,strong)NSTimer* playingTimer;//用于播放时间计时
//播放器
@property(nonatomic,strong)AudioPlayer * audioPlayer;
//时间转换为字符串
-(NSString*)secondsTurnTimeStr:(CGFloat)seconds;

@end

@implementation MusicPlayer

- (void)viewDidLoad {
    [super viewDidLoad];
    //加载页面相关
    [self viewLoad];
    //设置代理
    [self setDelegate];
    //slider的拖动事件
    [self.plyeingCours addTarget:self action:@selector(sliderAction:) forControlEvents:(UIControlEventValueChanged)];
    //设置导航栏上面的返回按钮
    UIBarButtonItem * item = [[UIBarButtonItem alloc] initWithTitle:@"返 回" style:(UIBarButtonItemStylePlain) target:self action:@selector(backAction)];
    self.navigationItem.leftBarButtonItem = item;
    
}
#pragma mark - 播放/暂停
- (IBAction)playButton:(id)sender {
    //播放按钮文字改变
    if (self.audioPlayer.isPlaying) {
        [self.playButton setTitle:@"播放" forState:(UIControlStateNormal)];
    }else{
         [self.playButton setTitle:@"暂停" forState:(UIControlStateNormal)];
    }
    //调用暂停/播放方法
    [self.audioPlayer playOrPause];
}
#pragma mark - 音量控制
- (IBAction)volumeControl:(UISlider *)sender {
    //设置音量
    self.audioPlayer.volume = sender.value;
}
#pragma mark - 播放进度控制
-(void)sliderAction:(UISlider*)sender{
    //调整音频
    [self.audioPlayer seekToWithTime:sender.value];
}
#pragma mark - 上一首/下一首
//上一首
- (IBAction)upOne:(UIButton *)sender {
    //判断--第一首则调到最后一首
    if (numberOfIndexPath == 0) {
        numberOfIndexPath = self.allDataArray.count - 1;
    }else{
        //位置指到上一首
        numberOfIndexPath--;
    }
    //更改界面信息
    [self songChangOfViewDidLoad];
}
//下一首
- (IBAction)downOne:(UIButton *)sender {
    //判断--最后首则跳到第一首
    if (numberOfIndexPath == self.allDataArray.count - 1) {
        numberOfIndexPath = 0;
    }else{
        //位置指到上一首
        numberOfIndexPath++;
    }
    //更改界面信息
    [self songChangOfViewDidLoad];
}
#pragma mark - 停止
- (IBAction)stopButton:(UIButton *)sender {
    [self.audioPlayer stop];
    //界面加载
    //改变播放按钮的文字
    [self.playButton setTitle:@"播放" forState:(UIControlStateNormal)];
    //播放时间
    self.playingTime.text = @"00:00";
    //剩余播放的时间
    self.durationTime.text = [self secondsTurnTimeStr:[self currentModel].duration/1000];
    //播放进度条
    self.plyeingCours.value = 0;
}

#pragma mark - 界面加载/代理设置
//界面信息的初次加载
-(void)viewLoad{
    //改变播放按钮的文字
    [self.playButton setTitle:@"暂停" forState:(UIControlStateNormal)];
    //图片设置成圈
    [[self.musicImage layer] setMasksToBounds:YES];
    [self.musicImage layer].borderWidth = 0.5;
    [self.musicImage layer].cornerRadius = 100;
    //位置信息赋值
    numberOfIndexPath = self.indexPath.row;
    //赋值图片
    self.musicImage.image = self.image;
    //歌名赋值
    self.songName.text = self.model.name;
    //初始化播放器(单例)
    self.audioPlayer = [AudioPlayer shareAudioPlayer];
    //获取音频
    NSString * mp3Url = self.model.mp3Url;
    //播放音频
    [self.audioPlayer playWithUrl:mp3Url];
    //修改slider的最大值
    self.plyeingCours.maximumValue = [self currentModel].duration/ 1000;
    //处理歌词
    LyricTool * lytool = [LyricTool ShareLyTool];
    [lytool lyricWithStr:[self currentModel].lyric];
    
}
//设置代理
-(void)setDelegate{
    self.audioPlayer.delegate = self;
    self.tebleView.delegate = self;
    self.tebleView.dataSource = self;
}
//歌曲切换，同时界面信息更换
-(void)songChangOfViewDidLoad{
    
    //获取该位置的模型数据
    MusicMode * model = self.allDataArray[numberOfIndexPath];
    //取到图片
    NSURL * urlImage = [NSURL URLWithString:model.picUrl];
    NSData *data = [NSData dataWithContentsOfURL:urlImage];
    self.musicImage.image = [UIImage imageWithData:data];
    //更改歌名
    self.songName.text = model.name;
    //进度条赋初值
    self.plyeingCours.value = 0;
    //音量同步
    self.audioPlayer.volume = self.volumeDisplay.value;
    //取到音频并播放
    [self.audioPlayer playWithUrl:model.mp3Url];
    //修改slider的最大值
    self.plyeingCours.maximumValue = [self currentModel].duration/ 1000;
    //处理歌词
    LyricTool * lytool = [LyricTool ShareLyTool];
    //删除上一首歌的歌词数据
    [[LyricTool ShareLyTool].modelArr removeAllObjects];
    //获取下一首歌的歌词数据
    [lytool lyricWithStr:[self currentModel].lyric];
    //重新加载界面
    [self.tebleView reloadData];
}

#pragma mark - audioPlayer的代理方法
//播放结束
-(void)playFinish
{
    //播放结束
    [self downOne:nil];
}
//播放过程中
-(void)playWithTime:(CGFloat)time
{
    //图片旋转
    self.musicImage.transform = CGAffineTransformRotate(self.musicImage.transform, 0.01);
    //播放时间
    self.playingTime.text = [self secondsTurnTimeStr:time];
    //剩余播放的时间
    self.durationTime.text = [self secondsTurnTimeStr:[self currentModel].duration/1000 - time];
    //播放进度条
    self.plyeingCours.value = time;
    //存储播放进度
    timeOfSongPlaying = time;
    //现在应该执行那句歌词
    NSInteger index = [[LyricTool ShareLyTool]indexForTime:time];
    if (index > 0) {
        //获取到当前要播放的歌词的下标
        self.singingIndex = [NSIndexPath indexPathForRow:index inSection:0];
    
        [self.tebleView scrollToRowAtIndexPath:self.singingIndex atScrollPosition:(UITableViewScrollPositionMiddle) animated:YES];
        [self.tebleView reloadData];
    }else{
        self.singingIndex = [NSIndexPath indexPathForRow:0 inSection:0];
        
        [self.tebleView scrollToRowAtIndexPath:self.singingIndex atScrollPosition:(UITableViewScrollPositionMiddle) animated:NO];
        [self.tebleView reloadData];

    }
}
#pragma mark - 时间转换成字符串
-(NSString*)secondsTurnTimeStr:(CGFloat)seconds
{
    int minutes = seconds / 60;
    int second = (int)seconds % 60;
    return [NSString stringWithFormat:@"%02d:%02d",minutes,second];
}
#pragma mark - 获取当前歌曲model
-(MusicMode*)currentModel{
    return self.allDataArray[numberOfIndexPath];
}
#pragma mark - tableView代理方法
//返回细胞个数
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [LyricTool ShareLyTool].modelArr.count;
}
//返回细胞
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //细胞重用池
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"UITableView"];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:@"UITableView"];
    }
    //取到要播放的歌词
    LyricTool*model = [LyricTool ShareLyTool].modelArr[indexPath.row];
    cell.textLabel.text = model.ly;
    cell.textLabel.textAlignment = NSTextAlignmentCenter;
    cell.textLabel.lineBreakMode = 2;
    //改变cell的颜色，正在播放的为红色，其他的为白色
    if (self.singingIndex == indexPath) {
        cell.backgroundColor = [UIColor greenColor];
        cell.textLabel.font = [UIFont systemFontOfSize:20];
    }else{
        cell.backgroundColor = [UIColor whiteColor];
        cell.textLabel.font = [UIFont systemFontOfSize:15];
    }
    return cell;
}

#pragma mark - block
-(void)sendIndex:(IndexBlock)index
{
    self.indexBlock = index;
}
-(void)backAction
{
    //bolck获取属性
    self.indexBlock(numberOfIndexPath);
    
    
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
